﻿using Heng.Elements.Core.IOC;
using Heng.Elements.Core.Model.Infrastructure.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using Heng.Elements.Core.Model.Infrastructure.IOC;
using Heng.Elements.Core.Model.Infrastructure.Policy;
using Heng.Elements.Core.Model.Infrastructure.Messages;

namespace Heng.Elements.Core.Model.WebApi
{
    /// <summary>
    /// Entity Web Api controller.
    /// Provides base implementation based on EntityServiceBase.
    /// </summary>
    /// <typeparam name="TEntity"> Entity type. </typeparam>
    public abstract class EntityWebApiControllerBase<TEntity> : ApiController
        where TEntity : class, IEntity
    {
        public ServiceResponse<IEnumerable<TEntity>> GetAll()
        {
            var response = PolicyManager.Exec<IEnumerable<TEntity>>(res =>
                {
                    var service = Ioc.Instance.GetEntityServiceByEntityType<TEntity>();
                    var entRes = service.GetAll();

                    res.Merge(entRes);
                    return entRes.Data;
                });

            return response;
        }

        public ServiceResponse<TEntity> GetById(int id)
        {
            var response = PolicyManager.Exec<TEntity>(res =>
                {
                    var service = Ioc.Instance.GetEntityServiceByEntityType<TEntity>();
                    var entRes = service.GetById(id);
                    res.Merge(entRes);
                    return entRes.Data;
                });

            return response;
        }

        public ServiceResponse Put(TEntity ent)
        {
            var response = PolicyManager.Exec(res =>
                {
                    var service = Ioc.Instance.GetEntityServiceByEntityType<TEntity>();
                    var saveRes = service.Save(ent);
                    res.Merge(saveRes);
                });

            return response;
        }

        public ServiceResponse Post(TEntity ent)
        {
            var response = PolicyManager.Exec(res =>
                {
                    var service = Ioc.Instance.GetEntityServiceByEntityType<TEntity>();
                    var addRes = service.Add(ent);
                    res.Merge(addRes);
                });

            return response;
        }

        public ServiceResponse Delete(int id)
        {
            var response = PolicyManager.Exec(res =>
                {
                    var service = Ioc.Instance.GetEntityServiceByEntityType<TEntity>();
                    var delRes = service.Delete(id);
                    res.Merge(delRes);
                });

            return response;
        }
    }
}
